import { ReviewRolesService } from './../../../../@core/services/ReviewRoles/review-roles.service';
import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DValidateRules, DialogService, FormLayout, TableWidthConfig } from 'ng-devui';
import { SaleDeliver } from 'src/app/@core/data/sale';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import * as XLSX from 'xlsx';
import { SetDeliveryDateComponent } from '../../sales-order/set-delivery-date/set-delivery-date.component';
import { SelectInventoryComponent } from 'src/app/@shared/components/select-inventory/select-inventory.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { SelectCustomerComponent } from 'src/app/@shared/components/select-customer/select-customer.component';
import { environment } from 'src/environments/environment';
import { SelectOrderComponent } from '../select-order/select-order.component';
@Component({
  selector: 'app-sales-invoice-edit',
  templateUrl: './sales-invoice-edit.component.html',
  styleUrls: ['./sales-invoice-edit.component.scss']
})
export class SalesInvoiceEditComponent {
  Math = Math;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  saleDeliver: SaleDeliver =
    {
      saleDeliverId: null, // 销售发货单ID
      orderDate: null, // 订单日期
      saleDeliverNum: '', // 销售发货单号
      saleDeliverCustomerId: 0, // 客户ID
      chineseName: '', // 客户中文名
      customerAbbreviation: '', // 客户简称
      company: '', // 公司名
      customerContactName: '', // 客户联系人姓名
      customerContactPhone: '', // 客户联系电话
      salesmanName: '', // 销售员姓名
      departmentName: '', // 部门名称
      scheduledDeliverTime: null, // 预定发货时间
      deliverType: '', // 发货类型
      deliveryAddress: '', // 发货地址
      settlementMethodName: '', // 结算方式名称
      currencyName: '', // 货币名称
      collectionPeriodName: '', // 收款期限名称
      isInvoice: false, // 是否开发票
      note: '', // 备注
      isPush: false, // 是否推送
      isDeliver: false, // 是否发货
      isReceive: false, // 是否收货
      isCancellation: false, // 是否取消
      isPrint: false, // 是否打印
      createTime: null, // 创建时间
      createUser: '', // 创建用户
      amount: 0, // 金额
      taxAmount: 0, // 税额
      tax: 0, // 税率
      unTaxAmount: 0, // 不含税金额
      taxDiscountAmount: 0, // 税后折扣金额
      taxDiscount: 0, // 税后折扣
      discountAmount: 0, // 折扣金额
      files: [], // 文件列表
      fileRemarks: [], // 文件备注
      saleDeliverParts: [
        {
          saleDeliverPartPartId: null,
          partNum: '',
          scheduledDeliverTime: null,
          scheduledDeliverAmount: 0,
          saleDeliverPartWarehouseId: 0,
          saleDeliverPartPositionId: 0,
          priceWithTax: 0,
          priceWithoutTax: 0,
          taxRate: 0,
          discount: 1,
          discountPriceWithTax: 0,
          amountWithTax: 0,
          amountWithoutTax: 0,
          taxAmount: 0,
          discountAmountWithTax: 0,
          discountAmountWithoutTax: 0,
          discountTaxAmount: 0,
          note: '',
          saleOrderNum: '',
          saleOrderPartId: 0
        }
      ]
    };
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '200px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '规格型号',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '发货日期',
      width: '220px'
    },
    {
      field: '数量',
      width: '220px'
    },
    {
      field: '仓库',
      width: '220px'
    },
    {
      field: '仓位',
      width: '220px'
    },
    {
      field: '当前库位库存',
      width: '150px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '单价(含税)',
      width: '220px'
    },
    {
      field: '单价（不含税）',
      width: '150px'
    },
    {
      field: '税率（%）',
      width: '170px'
    },
    {
      field: '折扣（%）',
      width: '150px'
    },
    {
      field: '折扣单价（含税）',
      width: '150px'
    },
    {
      field: '含税金额',
      width: '150px'
    },
    {
      field: '不含税金额',
      width: '150px'
    },
    {
      field: '税额',
      width: '150px'
    },
    {
      field: '折扣不含税金额',
      width: '150px'
    },
    {
      field: '折扣含税金额',
      width: '150px'
    },
    {
      field: '折扣税额',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    },
    {
      field: '来源报价单号',
      width: '150px'
    }
  ];
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '发货日期',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '发货数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓库',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '仓位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '当前库位库存',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价(含税)',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价（不含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税率（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣单价（含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '销售单号',
        fieldType: 'text',
      },
    ]
  };
  saleOrderRules: { [key: string]: DValidateRules } = {
    saleOrderNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*订单号不能为空' },
        { minlength: 2, message: '*订单号长度至少为2' },
        { maxlength: 40, message: '*订单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*订单号不能包含空格' }
      ]
    },
    customerName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户不能为空' },
      ]
    },
    orderDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*单据日期不能为空' },
      ]
    },
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料不能为空' },
      ]
    },
    plannedShipmentDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*计划发货时间不能为空' },
      ]
    },
    deliveryDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*计划交货时间不能为空' },
      ]
    },
    priceWithTax: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料单价不能为空' },
      ]
    },
    quantity: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    },
    salesmanName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    }
  }
  customerLinkMan: any = [];
  msgs: Array<Object> = [];
  customerContact: any = {};
  currencyOptions: any = [];
  settlementMethodOptions: any = [];
  data: any;
  loadData: boolean;
  collectionPeriods: any;
  constructor(private DialogService: DialogService, private UserService: UserService, private CustomerService: CustomerService, private SalesService: SalesService, private MaterialService: MaterialService, private router: Router, private EncodeRulesService: EncodeRulesService, private dataSharingService: DataSharingService, private activatedRoute: ActivatedRoute, private StorehouseService: StorehouseService,private ReviewRolesService:ReviewRolesService) { }
  ngOnInit(): void {
    this.activatedRoute.params.subscribe((params: any) => {
      if (params.id) {
        this.SalesService.GetSaleDeliverById(params.id).subscribe((data: any) => {
          this.saleDeliver = data
          this.customerContact = { customerContactId: data.customerContactID, customerContactName: data.customerContactName }
          this.CustomerService.GetCustomerById(this.saleDeliver.saleDeliverCustomerId).subscribe((res: any) => {
            this.customerLinkMan = res.customerContacts
          })
          this.saleDeliver.orderDate = new Date(this.saleDeliver.orderDate)
          this.saleDeliver.scheduledDeliverTime = new Date(this.saleDeliver.scheduledDeliverTime)
          this.saleDeliver.saleDeliverParts.forEach((item: any) => {
            item.scheduledDeliverTime = new Date(item.scheduledDeliverTime)
            this.StorehouseService.GetIssuedPositionInventoryByPartNum(item.partNum,1,999).subscribe((data:any) =>{
             item.realTimeInventory = data.items.filter(part => part.positionId === item.saleDeliverPartPositionId && part.warehouseId === item.saleDeliverPartWarehouseId)[0].partPositionInventory
            })
          })
        }
        )
      }
    })
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((data: any) => {
      this.currencyOptions = data.items;
    })
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe((data: any) => {
      this.settlementMethodOptions = data.items;
    })
    this.CustomerService.GetPagedCollectionPeriod({})
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.saleDeliver.createUser = JSON.parse(userinfoString).username;
    }
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '收款'
    }).subscribe((data: any) => {
      this.collectionPeriods = data.items
    })
  }
  addRow(index: number, rowItem: any) {
    const newRowItem = { ...rowItem };
    this.saleDeliver.saleDeliverParts.splice(index + 1, 0, newRowItem);
    this.saleDeliver.saleDeliverParts[index + 1].saleDeliverPartPartId = null;
    this.saleDeliver.saleDeliverParts[index + 1].scheduledDeliverTime = rowItem.scheduledDeliverTime;
    this.saleDeliver.saleDeliverParts[index + 1].scheduledDeliverAmount = 0;
    this.calculateAmount(rowItem)
  }
  deleteRow(index: number) {
    this.saleDeliver.saleDeliverParts.splice(index, 1);
    if(this.saleDeliver.saleDeliverParts.length === 0){
      this.saleDeliver.saleDeliverParts.push(
        {
          saleDeliverPartPartId: 0,
          partNum: '',
          scheduledDeliverTime: undefined,
          scheduledDeliverAmount: 0,
          saleDeliverPartWarehouseId: 0,
          saleDeliverPartPositionId: 0,
          priceWithTax: 0,
          priceWithoutTax: 0,
          taxRate: 0,
          discount: 0,
          discountPriceWithTax: 0,
          amountWithTax: 0,
          amountWithoutTax: 0,
          taxAmount: 0,
          discountAmountWithTax: 0,
          discountAmountWithoutTax: 0,
          discountTaxAmount: 0,
          note: '',
          saleOrderNum: '',
          saleOrderPartId: 0
        }
      )
    }
    this.calculateTotal();
  }//删除行
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
    this.calculateTotal();
  }//税率改变
  quantityChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//数量改变
  priceWithTaxChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//含税单价改变
  discountChange(rowitem: any, value: number) {
    rowitem.discount = value / 100;
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//折扣改变
  calculateAmount(item: any): void {
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.amountWithTax = +(item.priceWithTax * item.scheduledDeliverAmount).toFixed(4);
    item.taxAmount = +((item.priceWithTax - item.priceWithoutTax) * item.scheduledDeliverAmount).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    item.discountPriceWithTax = +(item.priceWithTax * item.discount).toFixed(4);
    item.discountAmountWithoutTax = +(item.amountWithoutTax * item.discount).toFixed(4);
    item.discountTaxAmount = +(item.taxAmount * item.discount).toFixed(4);
    item.discountAmountWithTax = +(item.discountPriceWithTax * item.scheduledDeliverAmount).toFixed(4);
    this.calculateTotal();
  }
  calculateTotal() {
    this.saleDeliver.amount = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.scheduledDeliverAmount, 0).toFixed(6)); // 计算总数量
    this.saleDeliver.taxAmount = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.amountWithTax, 0).toFixed(6)); // 计算总含税金额
    this.saleDeliver.tax = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.taxAmount, 0).toFixed(6)); // 计算总税额
    this.saleDeliver.unTaxAmount = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.amountWithoutTax, 0).toFixed(6)); // 金额合计不含税
    this.saleDeliver.taxDiscountAmount = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.discountAmountWithTax, 0).toFixed(6)); // 税后折扣金额
    this.saleDeliver.taxDiscount = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.discountTaxAmount, 0).toFixed(6)); // 折扣金额含税
    this.saleDeliver.discountAmount = parseFloat(this.saleDeliver.saleDeliverParts.reduce((prev, cur) => prev + cur.discountAmountWithoutTax, 0).toFixed(6)); // 折扣不含税金额
  } // 计算总金额
  isStartApproval: boolean = false
  isStartApprovalChange() {
    this.isStartApproval = true
  }
  submit($event: any) {

    if ($event.valid) {
      this.saleDeliver.createTime = new Date()

      const data: SaleDeliver = {
        saleDeliverId: this.saleDeliver.saleDeliverId,
        orderDate: this.saleDeliver.orderDate,
        saleDeliverNum: this.saleDeliver.saleDeliverNum,
        saleDeliverCustomerId: this.saleDeliver.saleDeliverCustomerId,
        chineseName: this.saleDeliver.chineseName,
        customerAbbreviation: this.saleDeliver.customerAbbreviation,
        company: this.saleDeliver.company,
        customerContactName: this.saleDeliver.customerContactName,
        customerContactPhone: this.saleDeliver.customerContactPhone,
        salesmanName: this.saleDeliver.salesmanName,
        departmentName: this.saleDeliver.departmentName,
        scheduledDeliverTime: this.saleDeliver.scheduledDeliverTime,
        deliverType: this.saleDeliver.deliverType,
        deliveryAddress: this.saleDeliver.deliveryAddress,
        settlementMethodName: this.saleDeliver.settlementMethodName,
        currencyName: this.saleDeliver.currencyName,
        collectionPeriodName: this.saleDeliver.collectionPeriodName,
        isInvoice: this.saleDeliver.isInvoice,
        note: this.saleDeliver.note,
        isPush: this.saleDeliver.isPush,
        isDeliver: this.saleDeliver.isDeliver,
        isReceive: this.saleDeliver.isReceive,
        isCancellation: this.saleDeliver.isCancellation,
        isPrint: this.saleDeliver.isPrint,
        createTime: this.saleDeliver.createTime,
        createUser: this.saleDeliver.createUser,
        amount: this.saleDeliver.amount,
        taxAmount: this.saleDeliver.taxAmount,
        tax: this.saleDeliver.tax,
        unTaxAmount: this.saleDeliver.unTaxAmount,
        taxDiscountAmount: this.saleDeliver.taxDiscountAmount,
        taxDiscount: this.saleDeliver.taxDiscount,
        discountAmount: this.saleDeliver.discountAmount,
        files: this.saleDeliver.files,
        fileRemarks: this.saleDeliver.fileRemarks,
        saleDeliverParts: this.saleDeliver.saleDeliverParts.map((item: any) => ({
          saleDeliverPartPartId: item.saleDeliverPartPartId,
          partNum: item.partNum,
          scheduledDeliverTime: item.scheduledDeliverTime,
          scheduledDeliverAmount: item.scheduledDeliverAmount,
          saleDeliverPartWarehouseId: item.saleDeliverPartWarehouseId,
          saleDeliverPartPositionId: item.saleDeliverPartPositionId,
          priceWithTax: item.priceWithTax,
          priceWithoutTax: item.priceWithoutTax,
          taxRate: item.taxRate,
          discount: item.discount,
          discountPriceWithTax: item.discountPriceWithTax,
          amountWithTax: item.amountWithTax,
          amountWithoutTax: item.amountWithoutTax,
          taxAmount: item.taxAmount,
          discountAmountWithTax: item.discountAmountWithTax,
          discountAmountWithoutTax: item.discountAmountWithoutTax,
          discountTaxAmount: item.discountTaxAmount,
          note: item.note,
          saleOrderNum: item.saleOrderNum,
          saleOrderPartId: item.saleOrderPartId
        }
        ))
      }
      this.SalesService.UpdateSaleDeliver(data.saleDeliverId, data).subscribe((res: any) => {
        if(this.isStartApproval){
          this.ReviewRolesService.StartApprovalFlow('销售发货单审核流配置',[data.saleDeliverNum]).subscribe((data:any) => {
            this.showToast('success', '成功', '更新成功')
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-Invoice'])
            }, 1000);
          },error=>{
            this.showToast('error','失败','单据创建成功，流程启动失败')
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-Invoice'])
            }, 1000)
          }
        )
        }else{
          this.showToast('success', '成功', '更新成功')
        setTimeout(() => {
          this.router.navigate(['/pages/sales-master/sales-Invoice'])
        }, 1000);
        }
      }, (error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )
    } else {
      this.showToast('warn', '警告', '请按照要求填写表单')
    }
  }//提交
  selectCustomer(dialogtype?: string,reset?:boolean) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择客户',
      content: SelectCustomerComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.saleDeliver.saleDeliverCustomerId = results.modalContentInstance.selectData.customerId;
            this.saleDeliver.chineseName = results.modalContentInstance.selectData.chineseName;
            this.saleDeliver.customerAbbreviation = results.modalContentInstance.selectData.customerAbbreviation;
            this.customerLinkMan = results.modalContentInstance.selectData.customerContacts;
            this.saleDeliver.currencyName = results.modalContentInstance.selectData.customerCurrencyName;
            this.saleDeliver.settlementMethodName = results.modalContentInstance.selectData.customerSettlementMethodName;
            this.saleDeliver.collectionPeriodName = results.modalContentInstance.selectData.customerCollectionPeriodName;
            this.saleDeliver.deliveryAddress = results.modalContentInstance.selectData.invoiceAddress
            if (results.modalContentInstance.selectData.customerContacts.length > 0) {
              this.saleDeliver.customerContactName = results.modalContentInstance.selectData.customerContacts[0].customerContactName;
              this.saleDeliver.customerContactPhone = results.modalContentInstance.selectData.customerContacts[0].phone;
            }
            this.UserService.GetUserById(results.modalContentInstance.selectData.salesmanId).subscribe((data: any) => {
              this.saleDeliver.salesmanName = data.name;
              this.UserService.GetDepartmentById(data.departmentId).subscribe((data: any) => {
                this.saleDeliver.departmentName = data.name;
              })
            })
            if(reset){
              this.saleDeliver.saleDeliverParts = [
                {
                  saleDeliverPartPartId: null,
                  partNum: '',
                  scheduledDeliverTime: null,
                  scheduledDeliverAmount: 0,
                  saleDeliverPartWarehouseId: 0,
                  saleDeliverPartPositionId: 0,
                  priceWithTax: 0,
                  priceWithoutTax: 0,
                  taxRate: 0,
                  discount: 1,
                  discountPriceWithTax: 0,
                  amountWithTax: 0,
                  amountWithoutTax: 0,
                  taxAmount: 0,
                  discountAmountWithTax: 0,
                  discountAmountWithoutTax: 0,
                  discountTaxAmount: 0,
                  note: '',
                  saleOrderNum: '',
                  saleOrderPartId: 0
                }
              ]
              this.calculateAmount(this.saleDeliver.saleDeliverParts[0])
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectCustomerBefore(dialogtype?: string) {
    if(this.saleDeliver.saleDeliverParts[0].partNum&&this.saleDeliver.chineseName !== ""){
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: true,
        data: "",
        title: '',
        dialogtype: dialogtype,
        html: true,
        content: '<div style="color:#8a6d3b;font-size: 14px;">确定切换客户，这将会使您构建的物料行数据重置！</div>',
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.selectCustomer(null,true)

            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }else{
      this.selectCustomer()
    }
  }
  selectUser(dialogtype?: string) {
    if (this.saleDeliver.customerContactName != "") {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: "",
        title: '选择业务员',
        content: SelectUserComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {

              this.saleDeliver.salesmanName = results.modalContentInstance.selectData.name;
              this.UserService.GetDepartmentById(results.modalContentInstance.selectData.departmentId).subscribe((data: any) => {
                this.saleDeliver.departmentName = data.name;
              })
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    } else {
      this.showToast('error', '错误', '请先选择客户')
    }
  }
  slectLinkMan(event: any) {
    this.CustomerService.GetCustomerContactById(event.customerContactId).subscribe((data: any) => {

      this.saleDeliver.customerContactName = data.customerContactName
      this.saleDeliver.customerContactPhone = data.phone
    })
  }
  getImagesArray(fileURL: any): [] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  @ViewChild('fileInput') fileInput: any;
  onButtonClick() {
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput.nativeElement.click();
  }
  onFileChange(event: any) {
    const file = event.target.files[0]; // 获取选中的文件
    if (file) {
      this.readExcel(file); // 调用readExcel方法并传递文件对象
      event.target.value = '';
    }
  }
  readExcel(file: any) {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      // 假设我们只处理第一个工作表
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      // 将工作表转换为JSON
      const json = XLSX.utils.sheet_to_json(worksheet);

      json.forEach((item, index) => {
        this.saleDeliver.saleDeliverParts[index].partNum = item['物料编号'];
        this.MaterialService.getParts(null, null, item['物料编号'], 1, 1).subscribe(
          (data: any) => {
            this.saleDeliver.saleDeliverParts[index].priceWithTax = data.items[0].salePrice;
          }
        )
        this.saleDeliver.saleDeliverParts[index].scheduledDeliverAmount = item['数量'];
        this.saleDeliver.saleDeliverParts[index].scheduledDeliverTime = new Date(item['计划发货时间']);
        this.saleDeliver.saleDeliverParts[index].priceWithTax = item['单价'];
        this.saleDeliver.saleDeliverParts[index].taxRate = item['税率'];
        this.calculateAmount(this.saleDeliver.saleDeliverParts[index]);
        this.calculateTotal();
      })
    };
    reader.readAsArrayBuffer(file);
  }
  writeExcel() {
    const headers = ['物料编号', '数量', '计划发货时间', '单价', '税率', '备注'];
    const ws = XLSX.utils.aoa_to_sheet([headers]);
    const redFontStyle = { font: { color: { rgb: "#FF0000" } } };
    ws['A1'].s = redFontStyle;
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, '销售订单物料表.xlsx');
  }
  setDeliveryDate(dialogtype?: string) {
    let data = {
      display: false
    };
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
      data: data,
      title: '选择交货日期',
      content: SetDeliveryDateComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.plannedShipmentDate) {
              this.saleDeliver.saleDeliverParts.forEach((item) => {
                item.scheduledDeliverTime = results.modalContentInstance.form.plannedShipmentDate;
                results.modalInstance.hide();
              })
            } else {
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cancel() {
    this.router.navigate(['/pages/sales-master/sales-Invoice'])
  }
  SelectStorehouse(rowItem: any, dialogtype?: string) {
    if (rowItem.partNum == "") {
      this.showToast('error', '错误', '请先选择物料')
      return;
    }
    const results = this.DialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width: '1000px',
      title: '选择仓库',
      data: rowItem,
      content: SelectInventoryComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {

              rowItem.saleDeliverPartWarehouseId = results.modalContentInstance.selectData.warehouseId;
              rowItem.saleDeliverPartWarehouseName = results.modalContentInstance.selectData.warehouseName;
              rowItem.saleDeliverPartPositionId = results.modalContentInstance.selectData.positionId;
              rowItem.saleDeliverPartPositionName = results.modalContentInstance.selectData.positionName;
              rowItem.realTimeInventory = results.modalContentInstance.selectData.partPositionInventory;
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectOrder(dialogtype?: string) {
    const saleOrderPartId = this.saleDeliver.saleDeliverParts.map((item: any) => item.saleOrderPartId)
    const results = this.DialogService.open({
      id: 'Add',
      width: '1250px',
      backdropCloseable: true,
      data: saleOrderPartId,
      title: '选择销售订单',
      content: SelectOrderComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.filterRows) {
              if(this.checkCustomerIDs(results.modalContentInstance.filterRows)){
                if (results.modalContentInstance.filterRows.length > 1) {
                  this.SalesService.GetSaleOrderById(results.modalContentInstance.filterRows[0].saleOrderId).subscribe((data: any) =>{
                    this.CustomerService.GetCustomerById(data.customerID).subscribe((data: any) => {
                      this.customerLinkMan = data.customerContacts
                      this.saleDeliver.chineseName = data.chineseName
                      this.saleDeliver.customerAbbreviation = data.customerAbbreviation
                      this.saleDeliver.currencyName = data.customerCurrencyName
                      this.saleDeliver.settlementMethodName = data.customerSettlementMethodName
                      this.saleDeliver.collectionPeriodName = data.customerCollectionPeriodName
                      this.saleDeliver.deliveryAddress = data.invoiceAddress
                      this.saleDeliver.customerContactName = data.customerContacts[0].customerContactName
                      this.saleDeliver.customerContactPhone = data.customerContacts[0].phone
                      this.saleDeliver.saleDeliverCustomerId = data.customerId
                      this.customerContact = { customerContactId: data.customerContacts[0].customerContactId, customerContactName: data.customerContacts[0].customerContactName }
                      this.UserService.GetUserById(data.salesmanId).subscribe((data: any) => {
                        this.saleDeliver.salesmanName = data.name
                        this.UserService.GetDepartmentById(data.departmentId).subscribe((data: any) => {
                          this.saleDeliver.departmentName = data.name
                        })
                      })
                    })
                  })
                } else {
                  this.SalesService.GetSaleOrderById(results.modalContentInstance.filterRows[0].saleOrderId).subscribe((data: any) => {
                    this.CustomerService.GetCustomerById(data.customerID).subscribe((data: any) => {
                      this.customerLinkMan = data.customerContacts
                    })
                    this.saleDeliver.chineseName = data.customerName
                    this.saleDeliver.saleDeliverCustomerId = data.customerID
                    this.saleDeliver.customerAbbreviation = data.customerShortName
                    this.saleDeliver.currencyName = data.settlementCurrency
                    this.saleDeliver.settlementMethodName = data.settlementMethod
                    this.saleDeliver.collectionPeriodName = data.paymentTerm
                    this.saleDeliver.deliveryAddress = data.deliveryAddress
                    this.saleDeliver.salesmanName = data.salesman
                    this.saleDeliver.departmentName = data.department
                    this.saleDeliver.customerContactName = data.customerContact
                    this.customerContact = { customerContactId: data.customerContactID, customerContactName: data.customerContact }
                    this.saleDeliver.customerContactPhone = data.contactInfo
                    this.saleDeliver.note = data.remark
                  })
                }
                this.saleDeliver.saleDeliverParts = this.saleDeliver.saleDeliverParts.filter(part => part.partNum !== "" && part.partNum !== null);
                const saleDeliverItem = results.modalContentInstance.filterRows.map((item: any) => ({
                  saleDeliverPartPartId: item.saleOrderPartPartId,
                  partNum: item.partNum,
                  image: item.image,
                  partName: item.partName,
                  partType: item.partType,
                  description: item.description || '',
                  scheduledDeliverTime: new Date(item.plannedShipmentDate),
                  scheduledDeliverAmount: item.quantity - item.soldQuantity,
                  partUOM: item.partUOM,
                  priceWithTax: item.priceWithTax,
                  priceWithoutTax: item.priceWithoutTax,
                  quantity: item.quantity,
                  taxRate: item.taxRate,
                  discount: item.discount,
                  discountPriceWithTax: item.discountPriceWithTax,
                  amountWithTax: item.amountWithTax,
                  amountWithoutTax: item.amountWithoutTax,
                  taxAmount: item.taxAmount,
                  discountAmountWithTax: item.discountAmountWithTax,
                  discountAmountWithoutTax: item.discountAmountWithoutTax,
                  discountTaxAmount: item.discountTaxAmount,
                  note: item.partRemark,
                  saleOrderNum: item.saleOrderNum,
                  saleOrderPartId: item.saleOrderPartId
                }));
                this.saleDeliver.saleDeliverParts = this.saleDeliver.saleDeliverParts.concat(saleDeliverItem);
                this.saleDeliver.saleDeliverParts.forEach((item: any) => {
                  this.calculateAmount(item)
                  this.StorehouseService.GetIssuedPositionInventoryByPartNum(item.partNum,1,999).subscribe((data: any) => {
                    if (data.items.length > 0) {
                      item.saleDeliverPartWarehouseId = data.items[0].warehouseId;
                      item.warehouseName = data.items[0].warehouseName;
                      item.saleDeliverPartPositionId = data.items[0].positionId;
                      item.positionName = data.items[0].positionName;
                      item.realTimeInventory = data.items[0].partPositionInventory;
                    } else {
                      item.saleDeliverPartWarehouseId = null
                      item.warehouseName = null
                      item.saleDeliverPartPositionId = null
                      item.positionName = null;
                      item.realTimeInventory = 0
                    }
                  })
                })
                this.calculateTotal();
                results.modalInstance.hide();
              }else{
                this.showToast('error', '错误', '请选择相同客户的订单')
              }
            }
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ]
    })
  }
  checkCustomerIDs(customerRows:any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].saleOrder.customerID;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every((row: any) => row.saleOrder.customerID === firstCustomerID);
  }
}
